package com.gitee.cliveyuan.tools.data;

import com.gitee.cliveyuan.tools.Assert;
import com.gitee.cliveyuan.tools.FileTools;
import com.gitee.cliveyuan.tools.exception.CsvException;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.List;

/**
 * @author clive
 * Created on 2018/08/01
 * @since 1.0
 */
public class CsvTools {

    private static final Logger logger = LoggerFactory.getLogger(CsvTools.class);

    private final static String CSV = "csv";

    /**
     * 读入csv文件，解析后返回
     *
     * @param absoluteFilePath 文件绝对路径
     */
    public static List<String[]> readCsv(String absoluteFilePath, String encoding) throws CsvException {
        Assert.notBlank(absoluteFilePath, "csv file path is empty");
        File file = new File(absoluteFilePath);
        Assert.isTrue(file.exists(), "csv file not exists");
        List<String[]> list = Lists.newArrayList();
        try {
            String extension = FileTools.getExtension(absoluteFilePath);
            if (!CSV.equalsIgnoreCase(extension)) {
                throw CsvException.notSupport(extension);
            }
            List<String> lines = FileTools.readFileToStringList(file, encoding);
            lines.forEach(line -> list.add(line.split(",")));
        } catch (CsvException e) {
            throw e;
        } catch (Exception e) {
            logger.error("readCsv ", e);
            throw CsvException.failToParseCsv();
        }
        return list;
    }
}
